import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
  TouchableHighlight,
} from 'react-native';
import LanguageDao, { FLAG_LANGUAGE } from '../../expand/dao/LanguageDao'
import CheckBox from 'react-native-check-box'
import ArrayUtils from '../../util/ArrayUtils'
import ViewUtils from '../../util/ViewUtils'
import SortableListView from 'react-native-sortable-listview'
import { StackNavigator, TabNavigator } from 'react-navigation';

export default class SortKeyPage extends Component {
  static navigationOptions = ({ navigation }) => ({
    headerTitle: navigation.state.params.title,
    headerStyle: { backgroundColor: '#2196F3' },
    headerTitleStyle: { alignSelf: 'center', color: 'white' },
    gesturesEnabled: true,
  })

  constructor(props) {
    super(props);
    // 原始数组
    this.dataArray = [];
    // 排序结果应用到原始数组
    this.sortResultArray = [];
    // 筛选后的数组
    this.originalCheckedArray = [];
    this.state = {
      checkedArray: []
    }
  }

  componentDidMount() {
    this.languageDao = new LanguageDao(this.props.navigation.state.params.flag);
    this.loadData();
  }

  // 加载标签
  loadData() {
    this.languageDao.fetch()
      .then(result => {
        this.getCheckedItems(result)
      })
      .catch(error => {
        console.log(error);
      })
  }

  // 获取已经订阅的标签
  getCheckedItems(result) {
    this.dataArray = result;
    let checkedArray = [];
    for (let i = 0, len = result.length; i < len; i++) {
      let data = result[i];
      // 如果订阅了，则放进checkedArray
      if (data.checked)
        checkedArray.push(data)
    }
    this.setState({
      checkedArray: checkedArray,
    })
    this.originalCheckedArray = ArrayUtils.clone(checkedArray);
  }

  getSortResult() {
    this.sortResultArray = ArrayUtils.clone(this.dataArray);
    for (let i = 0, j = this.originalCheckedArray.length; i < j; i++) {
      let item = this.originalCheckedArray[i];
      let index = this.dataArray.indexOf(item);
      // 替换index元素
      this.sortResultArray.splice(index, 1, this.state.checkedArray[i]);
    }
  }

  // 与原来数组判断，是否有改变
  onSave() {
    // 获取新的数组
    this.getSortResult();
    this.languageDao.save(this.sortResultArray);
  }

  render() {
    return (
      <View style={styles.container}>
        <SortableListView
          data={this.state.checkedArray}
          order={Object.keys(this.state.checkedArray)}
          onRowMoved={(e) => {
            // 拖动时触发
            this.state.checkedArray.splice(e.to, 0, this.state.checkedArray.splice(e.from, 1)[0]);
            this.onSave();
            this.forceUpdate();
          }}
          renderRow={row => <SortCell data={row} {...this.props} />}
        />
      </View>
    )
  }
}

// 自定义标签样式
class SortCell extends Component {
  render() {
    return <TouchableHighlight
      underlayColor={'#eee'}
      style={this.props.data.checked ? styles.item : styles.hidden}
      {...this.props.sortHandlers}>
      <View style={{ marginLeft: 10, flexDirection: 'row' }}>
        <Image source={require('./img/ic_sort.png')} resizeMode='stretch' style={{
          opacity: 1,
          width: 20,
          height: 20,
          marginRight: 10,
          tintColor: '#2196F3'
        }} />
        <Text>{this.props.data.name}</Text>
      </View>
    </TouchableHighlight>
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f3f2f2'
  },
  hidden: {
    height: 0
  },
  item: {
    backgroundColor: "#F8F8F8",
    borderBottomWidth: 1,
    borderColor: '#eee',
    height: 50,
    justifyContent: 'center'
  },
  line: {
    flex: 1,
    height: 0.3,
    backgroundColor: 'darkgray',
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  image: {
    tintColor: '#2196F3',
    height: 16,
    width: 16,
    marginRight: 10,
  }, title: {
    fontSize: 20,
    color: '#ffffff'
  }
})